<template>
  <el-form ref="form" label-width="120px" :model="formData" :rules="rules" @submit.prevent="onFormSubmit">
    <el-form-item label="尝试次数" prop="failNumber">
      <el-input v-model.number="formData.failNumber" />

      <k-help>后台登陆可以尝试密码错误的次数,超出会被限制一定时间内的登陆</k-help>
    </el-form-item>

    <el-form-item label="限制登陆时间" prop="failLimitTime">
      <el-input v-model.number="formData.failLimitTime" />

      <k-help>超出密码错误次数限制登陆的时间，单位/秒</k-help>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" native-type="submit" :loading="subIng">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import KHelp from '@/components/help/KHelp.vue'
import { useConfigStore } from '@/store/config'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'SettingLogin',
  components: { KHelp },
  setup () {
    const configStore = useConfigStore()
    const subIng = ref(false)
    const form = ref(null)
    const formData = ref<LoginConfig>(configStore.data.login as any)
    const rules = {
      failNumber: [
        { required: true, message: '错误次数值不可为空' },
        { type: 'number', message: '数值必须为数字' }
      ],
      failLimitTime: [
        { required: true, message: '限制登陆时间不可为空' },
        { type: 'number', message: '时间必须为数字' }
      ]
    }

    // 监听配置值更新
    configStore.$subscribe((mutation, state) => {
      formData.value = state.data.login as any
    })

    // 表单提交
    const onFormSubmit = async () => {
      await (form.value as any).validate()
      subIng.value = true
      try {
        await configStore.saveData({
          login: formData.value
        })
        ElMessage.success('保存成功')
      } catch (e) {
        ElMessage.error(e.message)
      } finally {
        subIng.value = false
      }
    }
    return {
      form,
      formData,
      rules,
      subIng,
      onFormSubmit
    }
  }
})
</script>
